<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽: 状态区域 -->
          <template slot-scope="scope">
            <!-- 将 Boolean 渲染为开关 -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175px">
          <!-- 作用域插槽: 操作区域 -->
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditUserDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页区域 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 5, 10, 20]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="50%" @close="addUserDialogClosed">
      <!-- 对话框内容主体区域 -->
      <el-form ref="addUserFormRef" :model="addUserForm" :rules="addUserFormRules" label-width="80px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPassword">
          <el-input type="password" v-model="addUserForm.checkPassword" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editUserDialogVisible" width="50%" @close="editUserDialogClosed">
      <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <el-form label-width="150px">
        <el-form-item label="当前用户: " label-width="30%">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前用户角色: " label-width="30%">
          <el-input v-model="userInfo.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配新角色: " label-width="30%">
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证两次密码结果
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.addUserForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    // 验证用户名不能重复
    var validateUsername = (rule, value, callback) => {
      // 假查询用户名:admin, 后端有查询接口后实现此功能
      if (value === 'admin') {
        callback(new Error('用户名已存在!'));
      }
      callback();
    }
    // 验证手机号
    var validateMobile = (rule, value, callback) => {
      const mobileReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,
        // 但是我实际用的时候输入的数字总是识别成字符串
        // 所以我就在前面加了一个+实现隐式转换
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (mobileReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    // 验证邮箱地址
    var validateEmail = (rule, value, callback) => {
      // 验证邮箱正则表达式
      const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      // 已选中的角色id值
      selectedRoleId: '',
      // 所有角色的列表对象
      rolesList: [],
      // 需要被分配角色的用户信息
      userInfo: {},
      // 控制分配角色对话框的开闭
      setRoleDialogVisible: false,
      // 用户列表的参数对象
      queryInfo: {
        // 查询条件(初始空串表示查询全部)
        query: '',
        // 当前页数(初始值)
        pagenum: 1,
        // 页面大小(显示多少条数据, 初始值: 5)
        pagesize: 5
      },
      // 用户列表
      userList: [],
      // 总数
      total: 0,
      // 控制添加用户对话框的显示与隐藏(默认是隐藏)
      addUserDialogVisible: false,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        checkPassword: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单的验证规则对象
      addUserFormRules: {
        username: [
          { required: true, message: '请输入新的用户名', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ]
      },
      // 修改用户对话框可见属性
      editUserDialogVisible: false,
      // 修改用户的对话框对象
      editUserForm: {},
      // 修改用户表单验证规则对象
      editUserFormRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 初始化用户数据列表
    this.getUserList()
  },
  methods: {
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    },
    // 点击按钮, 分配角色
    async saveRole () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择一个角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.setRoleDialogVisible = false
      this.getUserList()
    },
    // 展示分配角色的对话框
    async showSetRoleDialog (userInfo) {
      // 预先保存即将修改的用户信息对象
      this.userInfo = userInfo
      // 在展示对话框之前, 获取所有角色的列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // 保存角色列表
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 获取用户数据列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // **优化UI** this.$message.success(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize
    handleSizeChange (pageSize) {
      // console.log(pageSize);
      this.queryInfo.pagesize = pageSize
      this.getUserList()
    },
    // 监听 currentPage
    handleCurrentChange (currentPage) {
      // console.log(currentPage);
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    // 监听 switch, 并执行修改用户状态
    async userStateChanged (userInfo) {
      // console.log(userInfo);
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        // 保证页面原状态信息不会被错误污染
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 监听添加用户对话框的关闭事件
    addUserDialogClosed () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加新用户
    addUser () {
      // 表单预校验
      this.$refs.addUserFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) {
          return
        }
        // 持久化数据
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        }
        // 隐藏添加用户对话框
        this.addUserDialogVisible = false
        // 重新获取用户数据列表
        this.getUserList()
        this.$message.success(res.meta.msg)
      })
    },
    // 弹出编辑用户对话框
    async showEditUserDialog (userId) {
      // console.log(userId);
      // 调用根据id查询用户信息接口api
      const { data: res } = await this.$http.get('users/' + userId)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.editUserForm = res.data
      this.editUserDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editUserDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUser () {
      // 预验证
      this.$refs.editUserFormRef.validate(async valid => {
        // console.log(valid);
        // 判断并发出请求
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put('users/' + this.editUserForm.id, { email: this.editUserForm.email, mobile: this.editUserForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        // 隐藏对话框
        this.editUserDialogVisible = false
        // 重新获取列表
        this.getUserList()
        // 提示成功
        this.$message.success(res.meta.msg)
      })
    },
    // 删除用户
    async removeUser (userId) {
      // 弹框询问用户是否删除
      const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err) // 简写 { return err }
      // 确认返回confirm, 取消返回cancel
      // console.log(confirmRes);
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除操作')
      }
      const { data: res } = await this.$http.delete('users/' + userId)
      if (res.meta.status !== 200) {
        return this.$message.err(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
